﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace StockMarketTool
{
    /// <summary>
    /// AlertMsgWin.xaml 的交互逻辑
    /// </summary>
    public partial class AlertMsgWin : Window
    {
        SoundPlayer soundPlayer = null;
        Timer timer = null;
        private AlertMsgWin()
        {
            InitializeComponent();
            this.Left = SystemParameters.WorkArea.Width - 200;
            this.Top = SystemParameters.WorkArea.Height - 100;
            timer = new Timer();
            timer.Interval = 5000;
            timer.Elapsed += (s, e) =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    RunStb("stbHide", () => { this.Hide(); });
                });
            };
        }
        private static class HolderClass
        {
            public static volatile AlertMsgWin instance = new AlertMsgWin();
        }
        public static AlertMsgWin GetInstance()
        {
            AlertMsgWin win = null;
            Application.Current.Dispatcher.Invoke(() => { win = HolderClass.instance; });
            return win;
        }
        public void Show(string msg, bool playMusic = false)
        {
            Dispatcher.Invoke(() =>
            {
                tblMsg.Text = msg;
                this.Show();
                this.Activate();
                if (soundPlayer == null)
                {
                    soundPlayer = new SoundPlayer();
                    soundPlayer.Stream = Properties.Resources.tip;
                    soundPlayer.LoadAsync();
                }
                soundPlayer.Play();
                RunStb("stbShow", () =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        try
                        {
                            timer.Stop();
                            timer.Start();
                        }
                        catch { }
                    });
                });
            });

        }
        private void RunStb(string key, Action completed = null)
        {
            Storyboard stb = FindResource(key) as Storyboard;
            if (stb == null)
                return;
            if (completed != null)
                stb.Completed += (s, e) => { completed.Invoke(); };

            stb.Begin();
        }
    }
}